﻿using Batman.Cms.Core.Utils;
using Batman.Core.Utils;
using RabbitMQ.Client;
using System;
using System.Text;

namespace Batman.Jianbei.Forum.Core.RabbitMq
{
    public class RabbitMqSession : Abp.Dependency.ISingletonDependency
    {
        private ConnectionFactory _connectionFactory;

        public RabbitMqSession()
        {
            var userName = AppSettingsUtil.DefaultInstance.Get("RabbitMq:UserName");
            var password = AppSettingsUtil.DefaultInstance.Get("RabbitMq:Password");
            var HostName = AppSettingsUtil.DefaultInstance.Get("RabbitMq:HostName");

            _connectionFactory = new ConnectionFactory
            {
                UserName = userName,
                Password = password,
                HostName = HostName
            };
        }

        public ConnectionFactory GetFactory()
        {
            return _connectionFactory;
        }

        /// <summary>
        /// 生产消息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="exchangeName"></param>
        /// <param name="body"></param>
        public void BasicPublish<T>(string exchangeName, T body)
        {
            var bodyString = JsonUtil.Serialize(body);
            var bodyBytes = Encoding.UTF8.GetBytes(bodyString);
            BasicPublish(exchangeName, bodyBytes);
        }

        private void BasicPublish(string exchangeName, byte[] body)
        {
            using (var connection = _connectionFactory.CreateConnection())
            {
                using (var chanel = connection.CreateModel())
                {
                    chanel.BasicPublish(exchangeName, string.Empty, null, body);
                }
            }
        }

        public void Excute(Action<IModel> action)
        {
            using (var connection = _connectionFactory.CreateConnection())
            {
                using (var chanel = connection.CreateModel())
                {
                    action(chanel);
                }
            }
        }
    }
}
